package com.example.nio.component;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.example.nio.commons.Message;
import com.example.nio.commons.User;
import com.example.nio.service.MessageSendService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.util.Iterator;
import java.util.Map;

@Component
@ChannelHandler.Sharable
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


	Logger logger = LoggerFactory.getLogger(ChatHandler.class);

	private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Autowired
	private MessageSendService messageSendService;

	// 建立链接时 会触发的事件进入
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) {
//		for (Channel channel : channels) {
//			channel.writeAndFlush(new TextWebSocketFrame(ctx.channel().remoteAddress() + "进入聊天室"));
//		}
		System.out.println("用户建立了连接");
		channels.add(ctx.channel());
	}

	// 用户退出
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Iterator<Map.Entry<String, Channel>> iterator =  User.ipChannel.entrySet().iterator();
		String currentUser = null;
		while (iterator.hasNext()){
			Map.Entry<String, Channel> entry = iterator.next();
			if (entry.getValue().equals(ctx.channel())){
				currentUser = entry.getKey();
				User.ipChannel.remove(entry.getKey());
			}
		}
		Message message = new Message();
		message.setMsgType("userBroken");
		message.setContent("用户" + currentUser + "断开了连接");
		message.setFromUser(currentUser);
		messageSendService.messageHandling(message);
		logger.info("***用户断开了连接" + "的websocket断开");
	}

	// websocket收信息
	@Override
	protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		String content = msg.text();
		Channel ichannel = ctx.channel();

		Message message = JSONUtil.toBean(content, Message.class);

		if (message.getIsFirstSend() !=null && message.getIsFirstSend() == 1) {
			User.addUser(message.getFromUser(),ichannel);
			message.setContent("接入客服");
			message.setMsgType("text");
		}
		System.out.println("client收到消息："+content);
		System.out.println(User.ipChannel.toString());
		// 当消息不为空时 收消息
		if (!"".equals(message.getContent())){
			message.setSystemTime(System.currentTimeMillis());
			// 发送给客服（rabbitmq）
			messageSendService.messageHandling(message);
		}
	}
}
